package org.example.ruangong.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.Random;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender emailSender;
    @Value("${spring.mail.username}")
    private String fromEmail;

    public String sendSimpleMessage(String to, String subject, String text) {
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);
            emailSender.send(message);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("邮件发送失败");
            return "邮件发送失败";
        }
        return "邮件发送成功";

    }
    public  String generateCode(int length) {
        // 验证码字符集，可以根据需要添加或删除字符
        String charSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        // StringBuilder用于构建最终的验证码字符串
        StringBuilder code = new StringBuilder();

        // 创建一个Random对象用于生成随机数
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            // 从字符集中随机选择一个字符
            int index = random.nextInt(charSet.length());
            // 将选中的字符添加到StringBuilder中
            code.append(charSet.charAt(index));
        }

        return code.toString();
    }
}

